using Microsoft.SqlServer.Management.Smo;
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;

namespace Microsoft.SqlServer.Management.SqlManagerUI.Scripting
{
using Server = Microsoft.SqlServer.Management.Smo.Server;
	internal class ScriptUserCommand : ScriptObjectCommand
	{
		internal const string IfUserNotExistsOn90 = "IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'{0}')\r\nBEGIN\r\n{1}\r\nEND\r\n";

		internal const string IfUserNotExistsOn80 = "IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'{0}')\r\nBEGIN\r\n{1}\r\nEND\r\n";

		public ScriptUserCommand(Server server, ObjectScriptedHandler scriptTarget, ScriptActions scriptAction) : base(server, scriptTarget, scriptAction)
		{
		}

		protected override void ScriptCreate(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTarget)
		{
			if (!ScriptUserCommand.ShouldScriptUser(smoObject))
			{
				return;
			}
			DatabaseRole roleObject = ScriptUserCommand.GetRoleObject(smoObject);
			StringCollection stringCollection = new StringCollection();
			ReflectionUtilities.InvokeMethod(roleObject, "ScriptCreateInternal", new object[]
			{
				stringCollection,
				options
			});
			StringBuilder stringBuilder = new StringBuilder();
			foreach (string current in stringCollection)
			{
				stringBuilder.AppendLine(current);
			}
			string format = (options.TargetServerVersion == SqlServerVersion.Version80) ? "IF NOT EXISTS (SELECT * FROM dbo.sysusers WHERE name = N'{0}')\r\nBEGIN\r\n{1}\r\nEND\r\n" : "IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'{0}')\r\nBEGIN\r\n{1}\r\nEND\r\n";
			stringCollection = new StringCollection();
			stringCollection.Add(string.Format(CultureInfo.InvariantCulture, format, new object[]
			{
				roleObject.Name,
				stringBuilder.ToString()
			}));
			scriptTarget(new ObjectInfo(roleObject.Name, roleObject.Urn), stringCollection, ScriptActions.Create);
		}

		protected override void ScriptDrop(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTarget)
		{
		}

		protected override void ScriptPermission(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTarget)
		{
		}

		protected override void ScriptHeader(SqlSmoObject smoObject, ScriptingOptions options, ObjectScriptedHandler scriptTarget)
		{
			if (!ScriptUserCommand.ShouldScriptUser(smoObject))
			{
				return;
			}
			DatabaseRole roleObject = ScriptUserCommand.GetRoleObject(smoObject);
			base.ScriptHeader(roleObject, options, scriptTarget);
		}

		private static DatabaseRole GetRoleObject(SqlSmoObject smoObject)
		{
			User user = (User)smoObject;
			return new DatabaseRole(user.Parent, user.Name);
		}

		private static bool ShouldScriptUser(SqlSmoObject user)
		{
			return user is User && user != null && ((User)user).LoginType == LoginType.SqlLogin;
		}
	}
}
